<template>
    <div class="per">
        <Row class="margin-bottom-20 search">
            <Col span="2">
            <span class="middle-32 label">角色ID：</span>
            </Col>
            <Col span="5">
            <Input style="width:180px" placeholder="请输入角色ID" clearable v-model="roleArgs.search.id" :maxlength="11"/>
            </Col>
            <Col span="2">
                <span class="middle-32 label">角色名称：</span>
            </Col>
            <Col span="5">
                <!--<Input style="width:180px" placeholder="请输入角色名称" clearable v-model="roleArgs.search.roleName"  :maxlength="255"/>
                -->
               <!-- <Select v-model="roleArgs.search.id" clearable filterable placeholder="请选择角色名称" style="width:300px;">
                    <Option v-for="item in this.searchTb" :value="item.key" :key="item.key">{{ item.label }}</Option>
                </Select>-->
                <Input style="width:180px" placeholder="请输入角色名称" clearable v-model="roleArgs.search.roleName"/>
            </Col>
            <Col span="2">
                <span class="middle-32 label">角色状态：</span>
            </Col>
            <Col span="5">
                <Select v-model="roleArgs.search.enableStatus" clearable style="width:180px">
                    <Option v-for="item in moduleStatus" :value="item.value" :key="item.value">{{ item.label }}</Option>
                </Select>
            </Col>
            <Col span="2">
                <Button v-show="hasButtonPermission('101010201')" type="primary" @click="getPerTabl">查询</Button>
            </Col>
        </Row>
        <div class="margin-bottom-20">
            <Button v-show="hasButtonPermission('101010202')" type="ghost" @click="openAddRole"><Icon type="plus" class="margin-right-8"></Icon>新增</Button>
            <!--<Button type="ghost" @click="openAddRole" class="margin-left-15"><Icon type="edit" class="margin-right-8"></Icon>编辑</Button>-->
            <Button v-show="hasButtonPermission('101010204')" type="ghost" @click="openEditRelatePeople" class="margin-left-15"><Icon type="edit" class="margin-right-8"></Icon>编辑关联人员</Button>
            <Button v-show="hasButtonPermission('101010206')" type="ghost" @click="openDeleteModal" class="margin-left-15"><Icon type="close-round" class="margin-right-8"></Icon>批量删除</Button>
        </div>
        <div class="margin-bottom-20">
            <Table border :columns="prelistColumn" :data="prelistData" @on-selection-change="selectPersTables"></Table>
        </div>
        <Page :total="total" :current="currentPage" size="small" show-elevator show-sizer @on-change="pageChange" @on-page-size-change="pageSizeChange"></Page>
        <EditModal ref="EditModal" :data1="data1" @emitEditPerSuc="onPerSuc" :perInfo="selPer" ></EditModal>
        <AddModal ref="AddModal" :itemOpt="itemOpt" @emitAddPerSuc="onPerSuc"></AddModal>
        <EditRelatePeople ref="EditRelatePeople" :prelistDatas="prelistDatas" @emitEditPerSuc="onPerSuc" :perInfo="selPer" ></EditRelatePeople>
        <!--<EditRole ref="EditRole" @emitEditPerSuc="onPerSuc" :perInfo="selPer" style="display:none;"></EditRole>-->
        <Spin size="large" fix v-if="spinShow">加载中...</Spin>
    </div>
</template>
<script>
    import EditRole from '../addRole/editRole.vue'
    import EditModal from './modal/editModal.vue'
    import AddModal from './modal/addModal.vue'
    import EditRelatePeople from './modal/EditRelatePeople.vue'
    import {getRoleTableApi , getPerTableApi, deletePerApi, getPerMenuApi ,editpeopleApi ,getOrg_structApi} from '../../http/role.api'
    export default {
        name: 'role',
        components: {
            EditModal,
            AddModal,
            EditRelatePeople,
            EditRole
        },
        data () {
                return {
                    editRole: '',
                    //总条数
                    lengths: 0,
                    total: 0,
                    spinShow: false,
                    searchTb: [],
                    selectArry:[],
                    modulesArr: [],
                //表格的属性名
                columns1: [
                    {
                        title: '用户名',
                        key: 'employeeName'
                    },
                    {
                        title: '账户',
                        key: 'userName'
                    },
                    {
                        title: '所属部门',
                        key: 'orgStructId'
                    }
                ],
                data1: [],
                    // 角色key
                    prelistColumns: [
                        {
                            type: 'selection',
                            width: 60,
                            align: 'center'
                        },
                        {
                            title: '用户名',
                            width: 100,
                            key: 'employeeName',
                        },
                        {
                            title: '账户',
                            width: 100,
                            key: 'userName'
                        },
                        {
                            title: '部门',
                            width: 100,
                            key: 'orgStructId'
                        },
                        {
                            title: '状态',
                            key: 'status'
                        },
                        {
                            title: '联系方式',
                            width: 120,
                            key: 'contact'
                        },
                        {
                            title: '腾讯通',
                            width: 80,
                            key: 'rtx'
                        },
                        {
                            title: '邮箱',
                            width: 150,
                            key: 'email'
                        },
                        {
                            title: '创建时间',
                            width: 120,
                            key: 'createTime',
                        },
                        {
                            title: '操作',
                            key: 'action',
                            width: 100,
                            align: 'center',
                            render: (h, params) => {
                                return h('div', [
                                    h('Button', {
                                        props: {
                                            type: 'ghost',
                                            size: 'small'
                                        },
                                        style: {
                                            width:'50px',
                                            marginRight: '10px'
                                        },
                                        on: {
                                            click: () => {
                                                /*console.log(params)*/
                                                this.deleteOnePer({
                                                    id: params.row.id,
                                                    index: params.index
                                                })
                                            }
                                        }
                                    }, '删除')
                                ]);
                            }
                        }
                    ],
                    // 角色列表
                    prelistDatas: [],
                // 角色key
                prelistColumn: [
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center'
                    },
                    {
                        title: '角色ID',
                        key: 'id',
                    },
                    {
                        title: '角色名称',
                        key: 'roleName'
                    },
                    {
                        title: '备注',
                        key: 'comment'
                    },
                    {
                        title: '创建时间',
                        key: 'createTime',
                        sortable: true,
                        sortType:'desc',
                        render: (h, params) => {
                            if(!(params.row.createTime)){
                                return h('div', '')
                            }else {
                                var text = this.$moment(params.row.createTime).format('YYYY-MM-DD')
                                return h('div', text)
                            }
                        }
                    },
                     {
                        title: '角色状态',
                        key: 'enableStatus'
                    },
                    {
                        title: '关联人员数量',
                        key: 'employees',
                        render: (h, params) => {
                            return h('div', [
                                h('strong', params.row.employees?params.row.employees.length : 0),
                                h('Icon', {
                                    props: {
                                        type: 'person'
                                    },
                                    style: {
                                        width:'0px',
                                        marginLeft: '0px',
                                        position:'relative',
                                        left:'45px',
                                        zIndex:'1'
                                    }
                                }),
                                h('Div', {
                                    props: {
                                        type: 'text',
                                        size: '60',
                                        color:'blue'
                                    },
                                    style: {
                                        display:'inline-block',
                                        width:'35px',
                                        height:'17px',
                                        marginLeft: '30px',
                                        position:'relative',
                                        zIndex:'6',
                                        cursor: 'pointer'
                                    },
                                    on: {
                                        click: () => {
                                            /*console.log("params.row.id=="+params.row.id)*/
                                            // this.show(params.index)
                                           /* console.log(this.$refs.EditModal)*/
                                            this.getRole(params.row.id)
                                            this.selPer = params.row
                                            this.$refs.EditModal.editModal = true
                                        }
                                    }
                                })
                            ]);
                        }
                    },
                    {
                        title: '操作',
                        key: 'action',
                        width: 260,
                        align: 'center',
                        render: (h, params) => {
                            const _this = this;
                            return h('div', [
                                _this.hasButtonPermission('101010203') && h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        width:'50px',
                                        marginRight: '10px'
                                    },
                                    on: {
                                        click: () => {
                                            // this.show(params.index)
                                           /* console.log("params.row.id==="+params.row.id)*/
                                            this.selPer = params.row
                                            /*sessionStorage.setItem('selPer',JSON.stringify(params.row))*/
                                            this.openEditRole (params.row.id)
                                        }
                                    }
                                }, '编辑'),
                                _this.hasButtonPermission('101010207') && h('Button', {
                                    props: {
                                        type: 'info',
                                        size: 'small'
                                    },
                                    style: {
                                        width:'50px',
                                        marginRight: '10px'
                                    },
                                    on: {
                                        click: () => {
                                            // this.show(params.index)
                                           /* console.log(this.$refs.EditModal)*/
                                            this.selPer = params.row
                                           /* this.$refs.EditModal.editModal = true*/
                                            this.openCopyRole (params.row.id)
                                        }
                                    }
                                }, '复制'),
                                _this.hasButtonPermission('101010205') && h('Button', {
                                    props: {
                                        type: 'ghost',
                                        size: 'small'
                                    },
                                    style: {
                                        width:'50px',
                                        marginRight: '10px'
                                    },
                                    key: 'employees',
                                    on: {
                                        click: () => {
                                           /* console.log(params)*/
                                            if(params.row.employees){
                                                this.$Message.error("有关联人员，不能删除")
                                                return
                                            }
                                            this.deleteOnePer({
                                                id: params.row.id,
                                                index: params.index
                                            })
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                // 权限列表
                prelistData: [],
                moduleOpt: [
                    {
                        value: 'usermgt',
                        label: '用户管理模块'
                    }
                ],
                moduleType: [
                    {
                        value: 'general',
                        label: '普通角色'
                    },
                    {
                        value: 'system',
                        label: '系统角色'
                    }
                ],
                moduleStatus: [
                    {
                        value: 'true',
                        label: '启用'
                    },
                    {
                        value: 'false',
                        label: '禁用'
                    }
                ],
                itemOpt: [
                ],
                // 查询条件
                roleArgs: {
                    search: {
                        id: '',
                        roleName: '',
                        moduleCode: '',
                        roleType: '',
                        enableStatus:''
                    },
                    pageReqired: true,
                    limit: 10,
                    offset: 10,            // 偏移量
                    sort: 'createTime',   // 排序的字段
                    order: 'desc',        // asc 升序 desc 降序
                },
                selectPers: [], // 删除时选中的多条权限
                selPer: {}, // 编辑时选中的一条权限,
                currentPage: 1, // 当前页
                    isItems: false
            }
        },
        mounted () {
            this.getPerTable()//父页面的查询方法
            getPerMenuApi().then(suc => {
                this.itemOpt = []
                /*suc.data.map(datas => {
                    datas.menuLists.map(list => {
                        list.menuItems.map(item => {
                            this.itemOpt.push({
                                value: item.code,
                                label: item.name
                            })
                        })
                    })
                })*/
                this.isItems = true
                /*console.log('this.itemOpt', this.itemOpt)*/
            })
        },
        methods: {
            hasButtonPermission(permission) {
                return this.$store.getters['login/hasButtonPermission'](permission);
            },
            getPerTabl(){
                this.pageChanges(1)
                this.getPerTable ()
            },
            //角色关联人员
            getRole(id) {
                getRoleTableApi(id).then(resp => {
                    getOrg_structApi().then(suc => {
                        suc.data.result.map(datas => {
                            this.modulesArr.push({
                                value: datas.id,
                                label: datas.dept
                            })
                        })
                        this.data1 = (resp.data.result.employees)?(resp.data.result.employees) : []
                        if(this.data1) {
                            this.data1.map(listId => {
                                this.modulesArr.map(names => {
                                    if (listId.orgStructId == names.value) {
                                        listId.orgStructId = names.label
                                    }
                                })
                            })
                        }
                    })
                    if(resp.data.result.employees) {
                        resp.data.result.employees.map(li => {
                            if (li.orgStructId == 0) {
                                li.orgStructId = ''
                            }
                        })
                    }
                    this.spinShow = false
                }).catch(err => {
                    /*this.$Message.error("错误代码【"+err.data.code+"】，"+err.data.message)*/
                    this.spinShow = false
                })
            },
            //编辑关联人员
            getRoles(id) {
                getRoleTableApi(id).then(resp => {
                    this.prelistDatas = resp.data.result.employees||[]
                    this.spinShow = false
                }).catch(err => {
                    this.$Message.error("错误代码【"+err.data.code+"】，"+err.data.message)
                    this.spinShow = false
                })
            },
            // 查询权限列表
            getPerTable () {
                this.spinShow = true
                this.roleArgs.offset = (this.currentPage - 1) * this.roleArgs.limit
                const search = this.roleArgs.search
                search.id ? null :  delete search.id
                search.roleName ? null :  delete search.roleName
                search.moduleCode ? null :  delete search.moduleCode
                search.roleType ? null :  delete search.roleType
                search.enableStatus ? null :  delete search.enableStatus
                this.roleArgs.search = search
                getPerTableApi(this.roleArgs).then(resp => {
                    /*console.log(resp)*/
                    resp.data.rows.map(list => {
                        if(list.enableStatus==true){
                            list.enableStatus = '启用'
                        }else if(list.enableStatus==false){
                            list.enableStatus = '禁用'
                        }
                    })
                    this.prelistData = resp.data.rows

                   resp.data.rows.map(list => {
                       if(list.employees) {
                           this.lengths = list.employees.length
                           /*console.log("list.employees.length==" + list.employees.length)*/
                       }
                    })
                    this.total = resp.data.total
                    /*console.log("this.total====="+this.total)*/
                    this.spinShow = false
                }).catch(err => {
                    /*console.log("err= "+err)*/
                    this.$Message.error("错误代码【"+err.data.code+"】，"+err.data.message)
                    this.spinShow = false
                })
            },
            // 选中权限列表
            selectPersTables (arr) {
                this.selectPers = arr
            },
            // 切换页码
            pageChange (n) {
                this.currentPage = n
                this.getPerTable()
            },
            // 切换页码1
            pageChanges (n) {
                this.currentPage = n
            },
            // 切换每页显示数量
            pageSizeChange (n) {
                this.roleArgs.limit = n
                this.getPerTable()
            },
            // 删除多条权限
            deleteMorePer () {
                this.spinShow = true
                if (this.selectPers.length === 0) return
                Promise.all(this.selectPers.map(per => {
                    deletePerApi(per.id)
                    this.getPerTable()
                })).then(suc => {
                    /*console.log(suc)*/
                    this.getPerTable()
                    this.$Modal.remove()
                    this.spinShow = false
                }).catch(err => {
                    this.$Message.error("错误代码【"+err.data.code+"】，"+err.data.message)
                    this.$Modal.remove()
                    this.spinShow = false
                })
            },
            // 删除一条权限
            deleteOnePer (param) {
                this.$Modal.confirm({
                    title: '删除权限',
                    content: `<h4>说明:确定删除选中权限?</h4>`,
                    loading: true,
                    onOk: () => {
                        this.spinShow = true
                        deletePerApi(param.id).then(suc => {
                            /*console.log(suc)*/
                            this.getPerTable()
                            this.$Modal.remove()
                            this.spinShow = false
                        }).catch(err => {
                            this.$Message.error("错误代码【"+err.data.code+"】，"+err.data.message)
                            this.$Modal.remove()
                            this.spinShow = false
                        })
                    },
                    onCancel: () => {
                    }
                })
            },
            // 打开多删弹出框
            openDeleteModal (index) {
               /* console.log("this.selectPers6666.length===="+JSON.stringify(this.selectPers))*/
                const _this = this
                this.selectPers.map(it => ( _this.selectArry.push((it.employees)?(it.employees.length):0 )))
                /*console.log("_this.selectArry6666======="+_this.selectArry)*/
                /*console.log("length66======="+localStorage.getItem('employeesLength'))*/

                for(var i=0;i<_this.selectArry.length;i++){
                    if(_this.selectArry[i]>0){
                        this.$Message.error('有关联人员');
                        _this.selectArry = [];
                        return
                    }
                }
                /*if(localStorage.getItem('employeesLength')>0){
                    this.$Message.error('有关联人员');
                    return
                }*/

                if (this.selectPers.length === 0) {
                    this.$Message.config({
                        top: 260,
                        duration: 4
                    });
                    this.$Message.info('请勾选左边的复选框');
                    return
                }
                /*console.log("this.lengths==="+this.lengths)*/
                /*if(this.lengths){
                    this.$Message.error("有关联人员，不能删除")
                    return
                }*/
                this.selPer = this.selectPers[0]
                this.$Modal.confirm({
                    title: '删除权限',
                    content: `<h4>说明:确定删除选中权限?</h4>`,
                    loading: true,
                    onOk: () => {
                        this.spinShow = true
                        /*Promise.all([this.deleteMorePer(), this.getPerTable()]).then(function (res) { })*/
                        this.deleteMorePer()
                        this.getPerTable()
                        this.spinShow = false
                    },
                    onCancel: () => {
                    }
                })
            },
            // 打开添加角色
            openAddRole () {
                this.$router.push({ path: '/addRole'})
            },
            // 打开编辑角色
            openEditRole (id) {
                this.$router.push({ path: '/editRole/'+id})
            },
            // 复制角色
            openCopyRole (id) {
                /*this.$refs.CopyRole.copyRole = true*/
                this.$router.push({ path: '/copyRole/'+id})
            },
            // 打开编辑权限弹出框
            openEditModal () {
                if (this.selectPers.length === 1) {
                    /*if (this.selectPers.length === 0) return*/
                    this.$refs.EditModal.editModal = true
                }
            },
            // 打开编辑关联人员弹出框
            openEditRelatePeople () {
                if (this.selectPers.length === 0) {
                    this.$Message.config({
                        top: 260,
                        duration: 4
                    });
                    this.$Message.info('请勾选左边的复选框');
                    return
                }
                if (this.selectPers.length === 1) {
                    this.selPer = this.selectPers[0]
                    this.getRoles(this.selPer.id)
                    this.$refs.EditRelatePeople.editRelatePeople = true
                }else if(this.selectPers.length > 1){
                    this.$Message.error('只能勾选一个');
                }

            },
            // 权限添加成功事件
            onPerSuc () {
                console.log('--------权限添加成功！刷新列表！--------')
                this.getPerTable()
            }
        }
    }
</script>
<style>
    .clearfix::after {
        content: ".";
        clear: both;
        display: block;
        overflow: hidden;
        font-size: 0;
        height: 0;
    }
    .middle-32 {
        display: inline-block;
        height: 32px;
        line-height: 32px;
    }
    .search  .label {
        line-height: 32px;
        float: right;
    }
</style>
